package com.wfh.controller;


import com.wfh.common.BaseResponse;
import com.wfh.common.ResultUtils;
import com.wfh.model.dto.thumb.DoThumbRequest;
import com.wfh.service.ThumbService;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author FengHuan Wang
 * @Date 2025/4/18 19:33
 * @Version 1.0
 */
@RestController
@RequestMapping("thumb")
public class ThumbController {

    private final Counter successCounter;
    private final Counter failureCounter;

    public ThumbController(MeterRegistry registry) {
        this.successCounter = Counter.builder("thumb.success.count")
                .description("Total successful thumb")
                .register(registry);
        this.failureCounter = Counter.builder("thumb.failure.count")
                .description("Total failed thumb")
                .register(registry);
    }


    @Resource
    private ThumbService thumbService;

    /**
     * 博客点赞接口
     * @param doThumbRequest
     * @param request
     * @return
     */
    @PostMapping("/do")
    public BaseResponse<Boolean> doThumb(@RequestBody DoThumbRequest doThumbRequest, HttpServletRequest request){
        Boolean aBoolean = thumbService.doThumb(doThumbRequest, request);
        return ResultUtils.success(aBoolean);
    }

    /**
     * 取消点赞
     * @param doThumbRequest
     * @param request
     * @return
     */
    @PostMapping("/undo")
    public BaseResponse<Boolean> undoThumb(@RequestBody DoThumbRequest doThumbRequest, HttpServletRequest request){
        Boolean aBoolean = thumbService.undoThumb(doThumbRequest, request);
        return ResultUtils.success(aBoolean);
    }

    @PostMapping("/doview")
    public BaseResponse<Boolean> doViewThumb(@RequestBody DoThumbRequest doThumbRequest, HttpServletRequest request){
        try {
            Boolean res = thumbService.doThumb(doThumbRequest, request);
            if (res){
                // 记录成功数
                successCounter.increment();
                return ResultUtils.success(true);
            }else {
                // 记录失败数量
                failureCounter.increment();
                return ResultUtils.success(false);
            }
        } catch (Exception e) {
            // 记录失败计数
            failureCounter.increment();
            return ResultUtils.success(false);
        }
    }
}
